#include <QDebug>
#include <QFileDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QModelIndex>
#include <QStringList>

#include "Configuration.h"
#include "ManageDialog.h"
#include "Server.h"
#include "ui_ManageDialog.h"

ManageDialog::ManageDialog( Configuration *configuration, const ServerList *servers, QWidget *parent ) :
    QDialog(parent),
    ui( new Ui::ManageDialog ),
    mConfiguration( configuration ),
    mServers( servers )
{
    ui->setupUi( this );

    // Set current values.
    ui->minutes->setValue( mConfiguration->checkInterval() );
    ui->playSound->setChecked( mConfiguration->playSound() );
    ui->soundPath->setText( mConfiguration->alarmSoundPath() );
    ui->showPopup->setChecked( mConfiguration->showPopup() );

    refreshServerList();

    // Connect.
    connect( ui->deleteButton, SIGNAL(clicked()),
             this, SLOT(deleteServer()) );
    connect( ui->newButton, SIGNAL(clicked()),
             this, SLOT(newServer()) );
    connect( ui->saveButton, SIGNAL(clicked()),
             this, SLOT(saveServer()) );
    connect( ui->soundButton, SIGNAL(clicked()),
              this, SLOT(openSoundFile()) );
    connect( ui->buttonBox, SIGNAL(clicked(QAbstractButton*)),
            this, SLOT(save()) );
    connect( ui->serverList, SIGNAL(clicked(QModelIndex)),
             this, SLOT(serverClicked(QModelIndex)) );
}

ManageDialog::~ManageDialog()
{
    delete ui;
}

void ManageDialog::deleteServer()
{
     QModelIndex index = ui->serverList->currentIndex();
     if ( !index.isValid() )
     {
         return;
     }

    int button = QMessageBox::question( this,
                                        tr("Delete server"),
                                        tr("Do you really want to delete this server?"),
                                        QMessageBox::Yes | QMessageBox::No,
                                        QMessageBox::No );

    if ( button == QMessageBox::No )
    {
        return;
    }

    emit deleteServer( index.row() );
    refreshServerList();
}

void ManageDialog::newServer()
{
    QString name = QInputDialog::getText( this,
                                          tr("Pick a name."),
                                          tr("Please pick a name as a label for the server:") );

    if ( name.isEmpty() )
    {
        return;
    }

    QString url;
    QRegExp rx( "^(ht|f)tp(s?)\\:\\/\\/[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*(:(0-9)*)*(\\/?)([a-zA-Z0-9\\-\\.\\?\\,\\'\\/\\\\\\+&amp;%\\$#_]*)?$" );

    forever
    {
        url = QInputDialog::getText( this,
                                     tr("Enter url."),
                                     tr("Please enter the url of the server:") );

        if ( url.isEmpty() )
        {
            return;
        }

        if ( rx.indexIn(url) != -1 )
        {
            break;
        }
        else
        {
            QMessageBox::warning( this,
                                  tr("Incorrect url."),
                                  tr("This url is incorrect. Please enter a complete "
                                     "url with scheme, host...") );
        }
    }

    emit createServer( name, QUrl(url) );
    refreshServerList();
}

void ManageDialog::openSoundFile()
{
    QString dir = ui->soundPath->text();
    if ( dir.isEmpty() )
    {
        dir = QDir::homePath();
    }

    QString filePath;
    filePath = QFileDialog::getOpenFileName( this,
                                             tr("Select alarm sound"),
                                             dir,
                                             tr("Audio (*.wav)") );
    ui->soundPath->setText( filePath );
}

void ManageDialog::save()
{
    mConfiguration->setCheckInterval( ui->minutes->value() );
    mConfiguration->setPlaySound( ui->playSound->isChecked() );
    mConfiguration->setAlarmSoundPath( ui->soundPath->text() );
    mConfiguration->setShowPopup( ui->showPopup->isChecked() );
}

void ManageDialog::saveServer()
{
    QModelIndex index = ui->serverList->currentIndex();
    if ( !index.isValid() )
    {
        return;
    }

    ServerManager::ServerSettings settings;
    settings.maxPing = ui->maxPing->value();
    settings.url = QUrl(ui->url->text());
    settings.checkStats = ui->checkStats->isChecked();
    settings.maxLoad1 = ui->loadOne->value();
    settings.maxLoad5 = ui->loadFive->value();
    settings.maxLoad15 = ui->loadFifteen->value();

    emit editServer( index.row(), settings );
}

void ManageDialog::serverClicked( const QModelIndex &index )
{
    Server *server = mServers->at( index.row() );

    ui->url->setText( server->url().toString() );
    ui->maxPing->setValue( server->maxPing() );
    ui->checkStats->setChecked( server->checkStats() );
    ui->loadOne->setValue( server->maxLoadOne() );
    ui->loadFive->setValue( server->maxLoadFive() );
    ui->loadFifteen->setValue( server->maxLoadFifteen() );
}

void ManageDialog::refreshServerList()
{
    // Set server list.
    QStringList serverList;
    int size = mServers->size();
    for ( int i = 0; i < size; ++i )
    {
        serverList.append( mServers->at(i)->name() );
    }
    mModel.setStringList( serverList );
    ui->serverList->setModel( &mModel );
}
